package com.suqiu.common.exception.advice;

import com.suqiu.common.exception.SuqiuServiceException;
import com.suqiu.common.result.R;
import com.suqiu.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author suqiu
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.suqiu"})
public class SuqiuControllerAdvice {

    /**
     * 参数校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R methodArgumentNotValidExceptionAdvice(MethodArgumentNotValidException e) {
        List<String> strings = e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        return R.error(ResultCode.PARAM_BIND_ERROR.getCode(), strings.toString());
    }

    @ExceptionHandler(value = BindException.class)
    public R bindExceptionAdvice(BindException e) {
        List<String> strings = e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        return R.error(ResultCode.PARAM_BIND_ERROR.getCode(), strings.toString());
    }

    /**
     * 统一业务异常处理
     *
     * @return
     */
    @ExceptionHandler(value = SuqiuServiceException.class)
    public R serviceExceptionAdvice(SuqiuServiceException e) {
        return R.error(ResultCode.FAILURE.getCode(), e.getMessage());
    }

    /**
     * 所有异常统一处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public R AllExceptionAdvice(Exception e) {
        e.printStackTrace();
        return R.error("服务器异常");
    }
}
